package com.atguigu.lease.common.utils;


import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.exceptionhandler.BusException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.security.SignatureException;
import org.springframework.data.repository.query.QueryLookupStrategy;

import java.security.Key;
import java.util.Date;


public class JwtUtil {
//    对于一个token要么就是根据用户的重要信息作为负载 创建token
//    要么就是根据用户传递过来的token 解析出用户信息
//    token的负载一般包括 用户的唯一标识 比如用户id 或者用户名

    private static final Long TOKEN_TTL_TIME = 60 * 60 * 1000L;

//    在做秘钥的key的时候，我们传递的字符串要和加密的算法一样去做加密
    private static final Key signKey  = Keys.hmacShaKeyFor("495b4f316f0e512d07a98fba1fadef7796184383".getBytes());

    public static String createJWT(Long userId,String userName) {
        String token = Jwts
                .builder()
                .setSubject("lease-user-token")
                .setExpiration(new Date(System.currentTimeMillis() + TOKEN_TTL_TIME))
                .claim("userId", userId)
                .claim("userName", userName)
                .signWith(signKey)
                .compressWith(CompressionCodecs.GZIP)
                .compact();
        return token;
    }


//    Claims:{userId,userName}

    public static Claims parseToken(String token) {
        Jws<Claims> claimsJws = null;
        try {
            claimsJws = Jwts.parserBuilder()
                    .setSigningKey(signKey)
                    .build()
                    .parseClaimsJws(token);//拿负载
            return claimsJws.getBody();
        } catch (ExpiredJwtException e) {
            throw new BusException(ResultCodeEnum.TOKEN_EXPIRED);
        } catch (JwtException e) {
            throw new BusException(ResultCodeEnum.TOKEN_INVALID);
        }
    }
}
